<template>
    <div class="face">
        <video width="180" height="300" id="video" preload autoplay loop muted></video>
        <!-- <video width="360" height="620" id="videoshow" preload autoplay loop muted></video> -->
        <!-- <canvas width="360" height="620" id="videoshow"></canvas> -->
        <canvas width="180" height="300" id="canvas"></canvas>
        <img id="imageFile" >
    </div>
    
</template>

<script>
    import http from 'service/myhttp'
    export default {
        name: 'face',
        components: {},
        data() {
            return {
                msg: '登录',
                coresrc: '',
                login_info: {
                    account: null,
                    password: null,
                    yzm: null
                }
            }
        },
        methods: {
            cameratest: function() {
                console.log(navigator)
                navigator.mediaDevices.getUserMedia({
                    audio: false,
                    video: {
                        width: {
                            min: 360,
                            ideal: 720,
                            max: 1080
                        },
                        height: {
                            min: 600,
                            ideal: 1280,
                            max: 1920
                        }
                    }
                }).then(stream => {
                    console.log(stream)
                    var video = document.querySelector('#videoshow');
                    video.src = window.URL.createObjectURL(stream);
                    stream.onactive = function(e) {
                        console.info('dddd', e)
                        video.play();
                    }
                    // video.onloadedmetadata = function(e) {
                    //   // Do something with the video here.
                    //   video.play();
                    // };
                    video.play();
                }).catch(err => {
                    console.log(err)
                });
                // var captureSuccess = function(mediaFiles) {
                //   var i, path, len;
                //   for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                //     path = mediaFiles[i].fullPath;
                //     // do something interesting with the file
                //   }
                //   console.log(path)
                // };
                // // capture error callback
                // var captureError = function(error) {
                //   navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
                // };
                // // start image capture
                // navigator.device.capture.captureImage(captureSuccess, captureError, {
                //   limit: 2
                // });
                // var captureSuccess = function(mediaFiles) {
                //   var i, path, len;
                //   for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                //     path = mediaFiles[i].fullPath;
                //     // do something interesting with the file
                //   }
                //   console.log(path)
                // };
                // // capture error callback
                // var captureError = function(error) {
                //   navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
                // };
                // // start video capture
                // navigator.device.capture.captureVideo(captureSuccess, captureError, {
                //   limit: 2
                // });
                // window.navigator.camera.getPicture(res => {
                //   console.log(res)
                // }, err => {
                // })
            },
            createAndWriteimg: function(dataBlob) {
                //持久化图片保存
                console.info(window)
                window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, (dir) => {
                    var fs = dir.filesystem
                    console.info("文件夹", fs);
                    fs.root.getFile("face.png", {
                            create: true,
                            exclusive: false
                        },
                        (fileEntry) => {
                            var fullPath = fileEntry.toURL();
                            console.log(fullPath.toString() + '创建文件成功');
                            this.writeFile(fileEntry, dataBlob);
                        }, this.onErrorCreateFile);
                }, this.onErrorLoadFs);
            },
            //将内容数据写入到文件中
            writeFile: function(fileEntry, dataObj) {
                //创建一个写入对象
                fileEntry.createWriter((fileWriter)=> {
                    //文件写入成功
                    fileWriter.onwriteend = ()=> {
                        console.log("Successful file read...");
                         var elem = document.getElementById('imageFile');
                        elem.src = fileEntry.toURL();
                    };
                    //文件写入失败
                    fileWriter.onerror = (e)=> {
                        console.log("Failed file read: " + e.toString());
                    };
                    //写入文件
                    fileWriter.write(dataObj);
                });
            },
            //文件创建失败回调
            onErrorLoadFs: function(error) {
                console.info("文件夹读取失败！", error)
            },
            onErrorCreateFile: function(error) {
                console.info("文件创建失败！", error)
            }
        },
        mounted() {
            this.cameratest()
            var video = document.getElementById('video');
            var canvas = document.getElementById('canvas');
            // var videoshow = document.getElementById('videoshow')
            // var videoshow_contrl = videoshow.getContext('2d')
            var context = canvas.getContext('2d');
            var rat = window.innerWidth / canvas.width
            video.style.transform = 'scale(' + rat + ')'
            canvas.style.transform = 'scale(' + rat + ')'
            var tracker = new tracking.ObjectTracker('face');
            tracker.setInitialScale(4);
            tracker.setStepSize(2);
            tracker.setEdgesDensity(0.1);
            var trackerTask = tracking.track('#video', tracker, { //返回识别控制
                camera: true,
                fps: 1
            });
            tracker.on('track', (event) => {
                context.clearRect(0, 0, canvas.width, canvas.height);
                console.info('人脸', trackerTask.running_)
                event.data.forEach((rect) => {
                    context.strokeStyle = '#a64ceb';
                    context.strokeRect(rect.x, rect.y, rect.width, rect.height);
                    context.font = '11px Helvetica';
                    context.fillStyle = "#fff";
                    if (trackerTask.running_ && rect.width > 150 && rect.height > 150) { //判断扫描成功
                        context.drawImage(video, 0, 30, 180, 240);
                        trackerTask.stop()
                        var url
                        canvas.toBlob((blob) => {
                            this.createAndWriteimg(blob)
                        });
                        // var snapData = canvas.toDataURL('image/png')
                    }
                    // context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
                    // context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
                });
            });
        },
        beforeRouteEnter: function(to, from, next) {
            //路由钩子
            // console.log('enter')
            next()
        },
        beforeRouteLeave: function(to, from, next) {
            next()
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .face {
        width: 100%;
        height: 100%;
        position: relative;
        background: #000;
    }
    video,
    canvas {
        position: absolute;
        /* width: 320px;
                                                                        height: 400px; */
        left: 0;
        top: 0;
        transform-origin: left top;
    }
    #videoshow {
        z-index: 2000;
    }
    #canvas {
        z-index: 3000;
    }
</style>
